/*
	后台页面控制器
*/
var avArticle		= AV.Object.extend("Article");
var avContentGroup	= AV.Object.extend("ContentGroup");
var avImage 		= AV.Object.extend("Image");
var avPage			= AV.Object.extend("Page");
var avTemplet		= AV.Object.extend("Templet");

var moment		= require('moment');
var fs 			= require('fs');
var mdCommon	= require('cloud/modules/common.js');

var display		= function(res,tplFile) {
	mdCommon.display(res,fs,tplFile);
}

/**
 * 后台登录页面
 * 2015.04.18  by 胡斌
 */
exports.loginPage = function(req,res) {
	if(req.AV.user) return res.redirect('/admin/index');
    res.render('admin-login.html');
}

exports.getImage = function(req,res) {
	var returnData	= {};
	var queryImage 	= new AV.Query(avImage);

	queryImage.find().then(function(results) {
		returnData.results=[];
		for(var i=0;i<results.length;i++){
			returnData.results[i]={};
			returnData.results[i].url=results[i].get("url");
			returnData.results[i].id=results[i].id;
			returnData.results[i].content=results[i].get("content");
			returnData.results[i].title=results[i].get("title");
		returnData.results[i].username=results[i].get("username");	returnData.results[i].date=moment(results[i].get("createdAt")).format("YYYY-MM-DD");
		}
		//console.dir(returnData);
		res.json(returnData);
	},function(error){
		returnData.error=error;
		res.json(returnData);
	});
}

exports.getImageDetail = function(req,res) {
	var returnData	= {};
	var queryImage 	= new AV.Query(avImage);

	queryImage.get(req.query.id).then(function(result) {
		if(result){
		returnData.url=result.get("url");
		returnData.content=result.get("content");
		returnData.title=result.get("title");
	returnData.username=result.get("username");	returnData.date=moment(result.get("createdAt")).format("YYYY-MM-DD");
	}
		//console.dir(returnData);
		res.json(returnData);
	},function(error){
		returnData.error=error;
		res.json(returnData);
	});
}

/**
 * 后台索引页面
 * 2015.04.18  by 胡斌
 */
exports.indexPage = function(req, res) {
	res.render('admin-index.html',{
		user:req.AV.user
	});
}

/**
 * 用户列表页面
 * 2015.04.18  by 胡斌
 */
exports.userListPage = function(req, res) {
	var pager;

	var queryUser 	= new AV.Query(AV.User);
	queryUser.count().then(function(count){
		pager		= mdCommon.Paginate(req.query.page, req.query.pagesize, count);
		queryUser.skip((pager.currentPage-1)*pager.pagesize);
		queryUser.limit(pager.pagesize);
		return queryUser.find();
	}).then(function(results) {
		res.render('admin-user-list.html',{
			user:req.AV.user,
			results:results,
			moment:moment,
			pager:pager
		});
	});
}

/**
 * 用户详情页面
 * 2015.05.14  by 胡斌
 */
exports.userDetailPage = function(req, res) {
	var queryUser 	= new AV.Query(AV.User);
	var id			= req.query.id;

	queryUser.get(id).then(function(result) {
		res.render('admin-user-detail.html',{
			user:req.AV.user,
			result:result,
			moment:moment
		});
	},function(error) {
		mdCommon.sentErr(res,req,error);
	});
}

/**
 * 模板列表页面
 * 2015.04.19  by 胡斌
 */
exports.templetListpage = function(req, res) {
	var pager;
	var type	= req.query.type;
	if(typeof(type)=="undefined")type="html";

	var queryTemplet 	= new AV.Query(avTemplet);
	queryTemplet.descending("isForInclude");
	queryTemplet.addDescending("name");
	queryTemplet.equalTo("type",type);
	queryTemplet.count().then(function(count){
		pager		= mdCommon.Paginate(req.query.page, req.query.pagesize, count);
		queryTemplet.skip((pager.currentPage-1)*pager.pagesize);
		queryTemplet.limit(pager.pagesize);
		return queryTemplet.find();
	}).then(function(results) {
		res.render('admin-templet-list.html',{
			user:req.AV.user,
			results:results,
			moment:moment,
			type:type,
			pager:pager
		});
	},function(error) {
		mdCommon.sentErr(res,req,error);
	});

}

/**
 * 模版详情页面
 * 2015.05.02  by 胡斌
 */
exports.templetDetailPage = function(req, res) {
	var id				= req.query.id;
	var queryTemplet 	= new AV.Query(avTemplet);

	if(typeof(id)!="undefined"){
		queryTemplet.equalTo("objectId",id);
		queryTemplet.first().then(function(result) {
			res.render('admin-templet-detail.html',{
				user:req.AV.user,
				result:result,
				moment:moment
			});
		},function(error) {
			mdCommon.sentErr(res,req,error);
		});
	}else{
		var type	= req.query.type;
		if(typeof(type)=="undefined")type="html";
		res.render('admin-templet-detail.html',{
			user:req.AV.user,
			result:false,
			type:type,
			moment:moment
		});
	}
}

/**
 * 页面列表页面
 * 2015.05.02  by 胡斌
 */
exports.pageListpage = function(req, res) {
	var pager;
	var state	= req.query.state;

	var queryPage 	= new AV.Query(avPage);
	queryPage.ascending("title");
	queryPage.include("Templet");
	queryPage.count().then(function(count){
		pager		= mdCommon.Paginate(req.query.page, req.query.pagesize, count);
		queryPage.skip((pager.currentPage-1)*pager.pagesize);
		queryPage.limit(pager.pagesize);
		return queryPage.find();
	}).then(function(results) {
		res.render('admin-page-list.html',{
			user:req.AV.user,
			results:results,
			moment:moment,
			state:state,
			pager:pager
		});
	},function(error) {
		mdCommon.sentErr(res,req,error);
	});

}

/**
 * 页面详情页面
 * 2015.05.02  by 胡斌
 */
exports.pageDetailPage = function(req, res) {
	var templets,contentGroups;
	var id					= req.query.id;
	var queryPage 			= new AV.Query(avPage);
	var queryTemplet 		= new AV.Query(avTemplet);
	var queryContentGroup 	= new AV.Query(avContentGroup);

	queryContentGroup.ascending("title");
	queryContentGroup.find().then(function(results){
		contentGroups=results;
		queryTemplet.ascending("name");
		queryTemplet.equalTo("isForInclude",false);
		queryTemplet.equalTo("type","html");
		return queryTemplet.find();
	}).then(function(results){
		templets=results;
		if(typeof(id)!="undefined"){
			queryPage.equalTo("objectId",id);
			return queryPage.first();
		}else{
			return AV.Promise.as(false);
		}
	}).then(function(result) {
		if(typeof(result)=="undefined")result=false;

		res.render('admin-page-detail.html',{
			user:req.AV.user,
			result:result,
			templets:templets,
			contentGroups:contentGroups,
			moment:moment
		});
	},function(error) {
		mdCommon.sentErr(res,req,error);
	});
}

/**
 * 文章列表页面
 * 2015.05.02  by 胡斌
 */
exports.articleListpage = function(req, res) {
	var pager;
	var state	= req.query.state;

	var queryArticle 	= new AV.Query(avArticle);
	queryArticle.ascending("sort");
	queryArticle.addDescending("createdAt");

	if(typeof(state)=="undefined"){
		queryArticle.greaterThan("state",-1);
	}else{
		queryArticle.equalTo("state",state);
	}
	queryArticle.count().then(function(count){
		pager		= mdCommon.Paginate(req.query.page, req.query.pagesize, count);
		queryArticle.skip((pager.currentPage-1)*pager.pagesize);
		queryArticle.limit(pager.pagesize);
		return queryArticle.find();
	}).then(function(results) {
		res.render('admin-article-list.html',{
			user:req.AV.user,
			results:results,
			moment:moment,
			state:state,
			pager:pager
		});
	},function(error) {
		mdCommon.sentErr(res,req,error);
	});

}

/**
 * 文章详情页面
 * 2015.05.03  by 胡斌
 */
exports.articleDetailPage = function(req, res) {
	var id					= req.query.id;
	var groupID				= req.query.group;
	var queryArticle 		= new AV.Query(avArticle);
	var queryContentGroup 	= new AV.Query(avContentGroup);


	queryContentGroup.ascending("title");
	queryContentGroup.equalTo("type","Article");
	//queryContentGroup.equalTo("objectId",groupID);
	queryContentGroup.find().then(function(results){
		contentGroups=results;
		if(typeof(id)!="undefined"){
			queryArticle.include("cover");
			queryArticle.equalTo("objectId",id);
			return queryArticle.first();
		}else{
			return AV.Promise.as(false);
		}
	}).then(function(result) {
		if(typeof(result)=="undefined")result=false;

		res.render('admin-article-detail.html',{
			user:req.AV.user,
			result:result,
			contentGroups:contentGroups,
			group:groupID,
			moment:moment
		});
	},function(error) {
		mdCommon.sentErr(res,req,error);
	});
}

/**
 * 内容组列表页面
 * 2015.05.02  by 胡斌
 */
exports.contentGroupListpage = function(req, res) {
	var pager;

	var queryContentGroup 	= new AV.Query(avContentGroup);
	queryContentGroup.descending("createdAt");
	queryContentGroup.count().then(function(count){
		pager		= mdCommon.Paginate(req.query.page, req.query.pagesize, count);
		queryContentGroup.skip((pager.currentPage-1)*pager.pagesize);
		queryContentGroup.limit(pager.pagesize);
		return queryContentGroup.find();
	}).then(function(results) {
		res.render('admin-contentGroup-list.html',{
			user:req.AV.user,
			results:results,
			moment:moment,
			pager:pager
		});
	},function(error) {
		mdCommon.sentErr(res,req,error);
	});

}

/**
 * 内容组详情页面
 * 2015.05.03  by 胡斌
 */
exports.contentGroupDetailPage = function(req, res) {
	var ContentGroup,queryContent,pager,templets;
	var id					= req.query.id;
	var queryContentGroup 	= new AV.Query(avContentGroup);
	if(typeof(id)=="undefined")id="-1";

	queryContentGroup.equalTo("objectId",id);
	queryContentGroup.first().then(function(result){
		ContentGroup=result;

		var queryTemplet 		= new AV.Query(avTemplet);
		queryTemplet.ascending("name");
		queryTemplet.equalTo("isForInclude",false);
		queryTemplet.equalTo("type","html");
		return queryTemplet.find();
	}).then(function(results){
		templets=results;
		if(id!="-1"){
			if(ContentGroup.get("type")=="Article"){
				queryContent 		= new AV.Query(avArticle);
			}else{
				queryContent 		= new AV.Query(avArticle);
			}
			queryContent.contains("ContentGroup",id);
			return queryContent.count();
		}else{
			return AV.Promise.as(0);
		}
	}).then(function(count){
		pager	= mdCommon.Paginate(req.query.page, req.query.pagesize, count);
		if(count>0){
			queryContent.ascending("sort");
			queryContent.addDescending("createdAt");
			queryContent.skip((pager.currentPage-1)*pager.pagesize);
			queryContent.limit(pager.pagesize);
			return queryContent.find();
		}else{
			return AV.Promise.as([]);
		}
	}).then(function(results) {
		if(typeof(ContentGroup)=="undefined")ContentGroup=false;

		res.render('admin-contentGroup-detail.html',{
			user:req.AV.user,
			result:ContentGroup,
			results:results,
			templets:templets,
			moment:moment,
			pager:pager
		});
	},function(error) {
		mdCommon.sentErr(res,req,error);
	});
}

/**
 * 图片列表页面
 * 2015.05.04  by 胡斌
 */
exports.imageListpage = function(req, res) {
	var pager;

	var queryImage 	= new AV.Query(avImage);
	queryImage.descending("createdAt");
	queryImage.count().then(function(count){
		pager		= mdCommon.Paginate(req.query.page, req.query.pagesize, count);
		queryImage.skip((pager.currentPage-1)*pager.pagesize);
		queryImage.limit(pager.pagesize);
		return queryImage.find();
	}).then(function(results) {
		res.render('admin-image-list.html',{
			user:req.AV.user,
			results:results,
			moment:moment,
			pager:pager
		});
	},function(error) {
		mdCommon.sentErr(res,req,error);
	});

}

/**
 * 后台登录
 * 2015.04.18  by 胡斌
 */
exports.doLogin = function(req,res) {
	var queryUser = new AV.Query(AV.User);
	queryUser.equalTo("email",req.body.email);
	queryUser.equalTo("emailVerified",true);
	queryUser.first().then(function(user){
		if(typeof(user)=="object"){
			var crypto 	= require('crypto');
			var md5 	= crypto.createHash('md5');
			md5.update(req.body.password);
			return AV.User.logIn(user.get("username"), md5.digest('hex'));
		}else{
			return AV.Promise.error('用户不存在');//登录失败
		}
	}).then(function(username) {
		//跳转到profile页面。
		res.redirect('/admin/index');
    },function(error) {
		if(typeof(error)=="object"){
			error=error.message;
		}
		//登录失败，跳转到登录页面
		res.redirect('/admin-login',{
			error:error
		});
	});
}

/**
 * 后台登出
 * 2015.04.18  by 胡斌
 */
exports.doLogout = function(req,res) {
	AV.User.logOut();
    res.redirect('/admin-login');
}

/**
 * 后台登录页面
 * 2015.04.18  by 胡斌
 */
exports.doCkAuth = function(req,res,next) {
	if(!req.AV.user){// 判断用户是否已经登录
		res.redirect('/admin-login');
		return false;
	}else if(req.AV.user.get("roleName")!="admin"){
		res.redirect('/admin-logout');
		return false;
	}
	next();
}

/**
 * 新增用户
 * 2015.04.18  by 胡斌
 */
exports.doCreateUser = function(req,res) {
	var User;
	var name		= req.body.name;
	var email		= req.body.email;
	var queryUser 	= new AV.Query(AV.User);
	queryUser.equalTo("username",name);
	queryUser.count().then(function(count){
		if(count>0){
			return AV.Promise.error('该用户名已存在！');//
		}else{
			queryUser 	= new AV.Query(AV.User);
			queryUser.equalTo("email",email);
			return queryUser.count();
		}
	}).then(function(count){
		if(count>0){
			return AV.Promise.error("该邮箱已存在！");
		}else{
			var newUser 	= new AV.User();
			var crypto 	= require('crypto');
			var md5 	= crypto.createHash('md5');
			md5.update(req.body.password);
			newUser.set("password",md5.digest('hex'));
			newUser.set("username",name);
			newUser.set("email",email);
			newUser.set("roleName","user");
			return newUser.save();
		}
	}).then(function(result) {
		User			= result;
		var queryRole 	= new AV.Query(AV.Role);
		queryRole.equalTo("name","user");
		return queryRole.first();
    }).then(function(Role){
		if(typeof(Role)=="undefined"){
			return AV.Promise.error('默认角色不存在！');//
		}else{
			Role.getUsers().add(User);
			return Role.save();
		}
    }).then(function(Role) {
		res.redirect('/admin/user/list');
    },function(error) {
		mdCommon.sentErr(res,req,error);
	});
}

/**
 * 设置用户角色
 * 2015.05.04  by 胡斌
 */
exports.doSetUserRole = function(req,res) {
	var User;
	var id			= req.body.id;
	var roleName	= req.body.role;
	var queryUser 	= new AV.Query(AV.User);
	if(typeof(id)=="undefined")id="-1";

	queryUser.equalTo("objectId",id);
	queryUser.first().then(function(result){
		if(typeof(result)=="undefined"){
			return AV.Promise.error('用户不存在！');//
		}else if(result.id==req.AV.user.id){
			return AV.Promise.error('无法修改自身账号！');//
		}else if(result.get("protected")){
			return AV.Promise.error('无法修改受保护用户！');//
		}else{
			User			= result;
			var queryRole 	= new AV.Query(AV.Role);
			queryRole.equalTo("name",roleName);
			return queryRole.first();
		}
	}).then(function(Role){
		if(typeof(Role)=="undefined"){
			return AV.Promise.error('角色不存在！');//
		}else{
			Role.getUsers().add(User);
			return Role.save();
		}
	}).then(function(result){
		User.set("roleName",roleName);
		return User.save();
	}).then(function(User) {
		if(req.body.ajax){
			res.json({success:true});
		}else{
			res.redirect('/admin/user/list');
		}
    },function(error) {
		mdCommon.sentErr(res,req,error);
	});
}

/**
 * 用户管理-保存
 * 2015.05.15  by 胡斌
 */
exports.doSaveUser = function(req, res) {
	var User;
	var id			= req.body.id;
	var roleName	= req.body.roleName;
	var queryUser 	= new AV.Query(AV.User);
	if(typeof(id)=="undefined")id=-1;

	//console.log("id"+id);
	queryUser.equalTo("objectId",id);
	queryUser.first().then(function(result) {
		if(typeof(result)=="undefined"){
			return AV.Promise.error('用户不存在！');//
		}else if(result.id==req.AV.user.id){
			return AV.Promise.error('无法修改自身账号！');//
		}else if(result.get("protected")){
			return AV.Promise.error('无法修改受保护用户！');//
		}else{
			User			= result;
			var queryRole 	= new AV.Query(AV.Role);
			queryRole.containedIn("name",[roleName,User.get("roleName")]);
			return queryRole.find();
		}
	}).then(function(results){
		if(results.length<1 || (results.length==1 && results[0].get("name")!=roleName)){
			return AV.Promise.error('角色不存在！');//
		}else{
			console.dir("results.length="+results.length);
			console.dir(results[1]);

			if(results.length>1 && results[0].get("name")!=results[1].get("name")){
				if(results[0].get("name")==roleName){
					results[0].getUsers().add(User);
					results[1].getUsers().remove(User);
				}else{
					results[1].getUsers().add(User);
					results[0].getUsers().remove(User);
				}
				return AV.Promise.all([results[0].save(),results[1].save()]);
			}else{
				return AV.Promise.all([]);
			}
		}
	}).then(function(result){
		if(req.body.password.length>0){
			var crypto 	= require('crypto');
			var md5 	= crypto.createHash('md5');
			md5.update(req.body.password);
			User.set("password",md5.digest('hex'));
		}
		if(req.body.email!=User.get("email")){
			User.set("email",req.body.email);
		}
		User.set("username",req.body.username);
		User.set("roleName",roleName);
		return User.save();
	}).then(function(result) {
		if(req.body.ajax){
			res.json({result:result});
		}else{
			res.redirect('/admin/user/list');
		}
	},function(error){
		mdCommon.sentErr(res,req,error);
	});
}

/**
 * 删除用户
 * 2015.05.02  by 胡斌
 */
exports.doDeleteUser = function(req, res) {
	var id			= req.body.id;
	var queryUser 	= new AV.Query(AV.User);
	if(typeof(id)=="undefined")id="-1";

	queryUser.select("objectId","protected");
	queryUser.equalTo("objectId",id);
	queryUser.first().then(function(user){
		if(typeof(user)=="undefined"){
			return AV.Promise.error('用户不存在！');//
		}else if(user.id==req.AV.user.id){
			return AV.Promise.error('无法删除自身账号！');//
		}else if(user.get("protected")){
			return AV.Promise.error('无法删除受保护用户！');//
		}else{
			return user.destroy();
		}
	}).then(function(User) {
		if(req.body.ajax){
			res.json({success:true});
		}else{
			res.redirect('/admin/user/list');
		}
    },function(error) {
		mdCommon.sentErr(res,req,error);
	});
}

/**
 * 模版管理-保存
 * 2015.04.20  by 胡斌
 */
exports.doSaveTemplet = function(req, res) {
	var id				= req.body.id;
	var queryTemplet 	= new AV.Query(avTemplet);

	queryTemplet.equalTo("cacheName",req.body.cacheName);
	queryTemplet.equalTo("type",req.body.type);
	queryTemplet.find().then(function(results) {
		if(typeof(results)!="undefined" && (results.length>1 || (typeof(id)!="undefined" && results.length>0 && results[0].id!=id))){
			return AV.Promise.error('已经存在相同标识的模板了！');
		}else{
			if(typeof(id)!="undefined"){
				queryTemplet	= new AV.Query(avTemplet);
				queryTemplet.equalTo("objectId",id);
				return queryTemplet.first();
			}else{
				return AV.Promise.as(new avTemplet());
			}
		}
	}).then(function(Templet) {
		if(typeof(Templet)=="undefined"){
			Templet=new avTemplet();
			Templet.set("protected",false);
		}
		Templet.set("htmlContent",req.body.htmlContent);
		Templet.set("name",req.body.name);
		Templet.set("cacheName",req.body.cacheName);
		Templet.set("type",req.body.type);
		//console.log(Boolean(req.body.isForInclude));
		Templet.set("isForInclude",Boolean(req.body.isForInclude));
		return Templet.save();
	}).then(function(result) {
		//console.dir(result);
		var fn='/tmp/views/'+req.body.cacheName+"."+req.body.type;
		if(typeof(result)!="undefined" && fs.existsSync(fn)){
			//fs.unlinkSync('/tmp/views/'+req.body.cacheName+"."+req.body.type);
			fs.unlink(fn, function(err){
				if(err){
					console.err(err);
				}
			});
		}
		if(req.body.ajax){
			res.json({result:result});
		}else{
			res.redirect('/admin/templet/list?type='+req.body.type);
		}
	},function(error){
		mdCommon.sentErr(res,req,error);
	});
}

/**
 * 模版管理-删除
 * 2015.05.02  by 胡斌
 */
exports.doDeleteTemplet = function(req, res) {
	var Templet;
	var id					= req.body.id;
	var queryTemplet 		= new AV.Query(avTemplet);
	var queryContentGroup 	= new AV.Query(avContentGroup);
	var queryPage 			= new AV.Query(avPage);
	if(typeof(id)=="undefined")id=-1;

	queryTemplet.select("objectId","protected");
	queryTemplet.equalTo("objectId",id);
	queryTemplet.first().then(function(result){
		Templet=result;
		if(typeof(Templet)=="undefined"){
			return AV.Promise.error('模板不存在！');//
		}else if(Templet.get("protected")){
			return AV.Promise.error('无法删除受保护模板！');//
		}else{
			queryContentGroup.equalTo("Templet",Templet);
			queryPage.equalTo("Templet",Templet);
			return AV.Promise.when(queryContentGroup.find(),queryPage.find());
		}
	}).then(function(p1,p2) {
		//console.dir(p1);
		//console.dir(p2);
		if(p1.length==0 && p2.length==0){
			fs.unlinkSync('/tmp/views/'+Templet.get("cacheName")+"."+Templet.get("type"));
			return Templet.destroy();
		}else{
			return AV.Promise.error('删除失败，模板已被引用！');
		}
    }).then(function(result) {
		if(req.body.ajax){
			res.json({success:true});
		}else{
			res.redirect('/admin/templet/list');
		}
    },function(error) {
		mdCommon.sentErr(res,req,error);
	});
}

/**
 * 页面管理-保存
 * 2015.05.03  by 胡斌
 */
exports.doSavePage = function(req, res) {
	var id			= req.body.id;
	var queryPage 	= new AV.Query(avPage);

	queryPage.equalTo("name",req.body.name);
	queryPage.find().then(function(results) {
		if(typeof(results)!="undefined" && (results.length>1 || (typeof(id)!="undefined" && results.length>0 && results[0].id!=id))){
			return AV.Promise.error('已经存在相同标识的页面了！');
		}else{
			if(typeof(id)!="undefined"){
				queryPage	= new AV.Query(avPage);
				queryPage.equalTo("objectId",id);
				return queryPage.first();
			}else{
				return AV.Promise.as(new avPage());
			}
		}
	}).then(function(Page) {
		var ContentGroupArr=req.body.contentGroupArr;
		if(typeof(ContentGroupArr)=="string")ContentGroupArr=[];
		Templet		= new avTemplet();
		Templet.id	= req.body.templet;
		//console.log(typeof(ContentGroup));
		if(typeof(Page)=="undefined"){
			Page=new avPage();
			Page.set("protected",false);
		}
		Page.set("content",req.body.content);
		Page.set("name",req.body.name);
		Page.set("title",req.body.title);
		Page.set("Templet",Templet);
		Page.set("ContentGroup",req.body.contentGroup);
		Page.set("ContentGroupArr",ContentGroupArr);
		return Page.save();
	}).then(function(result) {
		if(req.body.ajax){
			res.json({result:result});
		}else{
			res.redirect('/admin/page/list');
		}
	},function(error){
		mdCommon.sentErr(res,req,error);
	});
}

/**
 * 页面管理-删除
 * 2015.05.02  by 胡斌
 */
exports.doDeletePage = function(req, res) {
	var id					= req.body.id;
	var queryPage 			= new AV.Query(avPage);
	if(typeof(id)=="undefined")id=-1;

	queryPage.select("objectId","protected");
	queryPage.equalTo("objectId",id);
	queryPage.first().then(function(result){
		if(typeof(result)=="undefined"){
			return AV.Promise.error('页面不存在！');//
		}else if(result.get("protected")){
			return AV.Promise.error('无法删除受保护页面！');//
		}else{
			return result.destroy();
		}
	}).then(function(result) {
		if(req.body.ajax){
			res.json({success:true});
		}else{
			res.redirect('/admin/page/list');
		}
    },function(error) {
		mdCommon.sentErr(res,req,error);
	});
}


/**
 * 文章管理-保存
 * 2015.05.24  by 胡斌
 */
exports.doSaveArticle = function(req, res) {
	var id				= req.body.id;
	var sort			= parseInt(req.body.sort);
	var queryArticle 	= new AV.Query(avArticle);
	if(typeof(id)=="undefined")id=-1;
	if(typeof(sort)!="number")sort=999;

	//console.log("id"+id);
	queryArticle.equalTo("objectId",id);
	queryArticle.first().then(function(Article) {
		var Image=null;
		var ContentGroup=req.body.contentGroup;
		if(typeof(ContentGroup)=="string")ContentGroup=[];
		//console.log("typeof(result)"+typeof(result));
		if(typeof(Article)=="undefined"){
			Article	= new avArticle();
		}
		if(typeof(req.body.cover)!="undefined" && req.body.cover.length>0){
			Image		= new avImage();
			Image.id	= req.body.cover;
		}

		Article.set("content",req.body.content);
		Article.set("description",req.body.description);
		Article.set("keyword",req.body.keyword.split("|"));
		Article.set("linkArticle",req.body.linkArticle.split(","));
		Article.set("ContentGroup",ContentGroup);
		Article.set("title",req.body.title);
		Article.set("author",req.body.author);
		Article.set("sort",sort);
		Article.set("state",parseInt(req.body.state));
		Article.set("cover",Image);
		return Article.save();
	}).then(function(result) {
		if(req.body.ajax){
			res.json({result:result});
		}else{
			res.redirect('/admin/article/list');
		}
	},function(error){
		mdCommon.sentErr(res,req,error);
	});
}

/**
 * 文章管理-删除
 * 2015.05.02  by 胡斌
 */
exports.doDeleteArticle = function(req, res) {
	var id					= req.body.id;
	var queryArticle 		= new AV.Query(avArticle);
	if(typeof(id)=="undefined")id=-1;

	queryArticle.select("objectId");
	queryArticle.equalTo("objectId",id);
	queryArticle.first().then(function(result){
		if(typeof(result)=="undefined"){
			return AV.Promise.error('文章不存在！');//
		}else{
			return result.destroy();
		}
	}).then(function(result) {
		if(req.body.ajax){
			res.json({success:true});
		}else{
			res.redirect('/admin/article/list');
		}
    },function(error) {
		mdCommon.sentErr(res,req,error);
	});
}

/**
 * 文章组管理-保存
 * 2015.05.02  by 胡斌
 */
exports.doSaveContentGroup = function(req, res) {
	var id					= req.body.id;
	var queryArticle 		= new AV.Query(avArticle);
	var queryContentGroup 	= new AV.Query(avContentGroup);

	queryContentGroup.equalTo("name",req.body.name);
	queryContentGroup.find().then(function(results) {
		if(typeof(results)!="undefined" && (results.length>1 || (typeof(id)!="undefined" && results.length>0 && results[0].id!=id))){
			return AV.Promise.error('已经存在相同标识的文章组了！');
		}else{
			if(typeof(id)!="undefined"){
				queryContentGroup	= new AV.Query(avContentGroup);
				queryContentGroup.equalTo("objectId",id);
				return queryContentGroup.first();
			}else{
				return AV.Promise.as(new avContentGroup());
			}
		}
	}).then(function(ContentGroup) {
		Templet		= new avTemplet();
		Templet.id	= req.body.templet;

		ContentGroup.set("Templet",Templet);
		ContentGroup.set("title",req.body.title);
		ContentGroup.set("name",req.body.name);
		ContentGroup.set("type",req.body.type);

		ContentGroup.set("perPage",parseInt(req.body.perPage));
		return ContentGroup.save();
	}).then(function(result) {
		if(req.body.ajax){
			res.json({result:result});
		}else{
			res.redirect('/admin/contentGroup/list');
		}
	},function(error){
		mdCommon.sentErr(res,req,error);
	});
}

/**
 * 文章组管理-删除
 * 2015.05.02  by 胡斌
 */
exports.doDeleteContentGroup = function(req, res) {
	var id					= req.body.id;
	var queryContentGroup 	= new AV.Query(avContentGroup);
	if(typeof(id)=="undefined")id=-1;

	queryContentGroup.select("objectId");
	queryContentGroup.equalTo("objectId",id);
	queryContentGroup.first().then(function(result){
		if(typeof(result)=="undefined"){
			return AV.Promise.error('文章不存在！');//
		}else{
			return result.destroy();
		}
	}).then(function(result) {
		if(req.body.ajax){
			res.json({success:true});
		}else{
			res.redirect('/admin/article/list');
		}
    },function(error) {
		mdCommon.sentErr(res,req,error);
	});
}
